using System.IO;
using System.Xml;
using System.Net;
using System.Web;
using System.Security.Cryptography.X509Certificates;

namespace com.paypal.wps.util
{
	/// <summary>
	/// Global helper methods.
	/// </summary>
	public class Utils
	{
		/// <summary>
		/// Creates an XmlElement from a stream
		/// </summary>
		/// <param name="stream"></param>
		/// <returns>XmlElement pointing to the root of the XML</returns>
		public static XmlElement CreateXmlNode(Stream stream)
		{
			XmlElement xmlElement;
			XmlDocument doc = new XmlDocument();
			using (stream)
			{
				doc.Load(stream);
			}
			xmlElement = doc.DocumentElement;
			return xmlElement;
		}

		/// <summary>
		/// Returns if a string is empty or null
		/// </summary>
		/// <param name="s">the string</param>
		/// <returns>true if the string is not null and is not empty or just whitespace</returns>
		public static bool IsEmpty(string s)
		{
			return s == null || s.Trim() == string.Empty;
		}

		/// <summary>
		/// Creates an XmlElement from a StreamReader
		/// </summary>
		/// <param name="streamReader">the xml input</param>
		/// <returns>XmlElement pointing to the root of the XML</returns>
		public static XmlElement CreateXmlNode(StreamReader streamReader)
		{
			XmlElement xmlNode;
			XmlDocument doc = new XmlDocument();
			using (streamReader)
			{
				doc.Load(streamReader);
			}
			xmlNode = doc.DocumentElement;
			return xmlNode;
		}

		public const int DEFAULT_HTTPPOST_TIMEOUT = 1000000;

		public static string HttpPost(string url, string postData)
		{
			return HttpPost(url, postData, DEFAULT_HTTPPOST_TIMEOUT, null);
		}

		public static string HttpPost(string url, string postData, int timeout, X509Certificate x509)
		{
			HttpWebRequest objRequest = (HttpWebRequest) WebRequest.Create(url);
			objRequest.Timeout = timeout;
			objRequest.Method = "POST";
			objRequest.ContentLength = postData.Length;
			if (null != x509)
			{
				objRequest.ClientCertificates.Add(x509);
			}
			using (StreamWriter myWriter = new StreamWriter(objRequest.GetRequestStream()))
			{
				myWriter.Write(postData);
			}
			using (WebResponse response = objRequest.GetResponse())
			{
				using (StreamReader sr = new StreamReader(response.GetResponseStream()))
				{
					return sr.ReadToEnd();
				}
			}
		}
	}
}
